package com.ygqh.baby.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ygqh.baby.ao.Message;
import com.ygqh.baby.po.AdminUser;
import com.ygqh.baby.utils.MailUtil;

public abstract class LogAspect {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	protected final ExecutorService threadPool = Executors.newFixedThreadPool(5);

	public abstract void controllerAspect();
	
	public abstract void simpleAdvice(JoinPoint jp, Message returnValue);

	protected String getOperator() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();    
        HttpSession session = request.getSession();    
        //读取session中的用户    
        AdminUser user = (AdminUser) session.getAttribute("currentUser");
        return user == null ? "" : user.getTrueName();
	}

	protected <T extends Annotation> T getAnnotation(JoinPoint joinPoint, Class<T> clazz) throws ClassNotFoundException {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class<?> targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class<?>[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					return method.getAnnotation(clazz);
				}
			}
		}
		return null;
	}
	
	protected void sendErrorToMail(MailUtil mailUtil, String subject, String methodName, String errorMsg) {
		StringBuilder html = new StringBuilder();
		html.append("methodName=").append(methodName).append(", error=").append(errorMsg);
		try {
			mailUtil.sendWithHtml(new String[]{"sunshuo@yiigoo.cn"}, subject, html.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
